package com.nforce.linremote.scripting;

import org.apache.commons.lang3.StringUtils;

import com.nforce.linremote.model.LFunction;
import com.nforce.linremote.model.Script;
import com.nforce.linremote.serverapi.Library;

public class LRMLParser {

    static final private String EXP_PREFIX = "%{";
    static final private String EXP_SUFFIX = "}";
    static final private String FUNCTION_SUFFIX = "()";

    static public String parseVars(String command, Script script) {
	String exprs[] = StringUtils.substringsBetween(command, EXP_PREFIX, EXP_SUFFIX);
	if (exprs == null) {
	    return command;
	}
	for (String e : exprs) {
	    if (e.endsWith(FUNCTION_SUFFIX)) {
		continue;
	    }
	    String replaceFrom = EXP_PREFIX + e + EXP_SUFFIX;
	    String replaceTo = script.getVar(e);
	    if (replaceTo != null) {
		command = command.replace(replaceFrom, replaceTo);
	    }
	}
	return command;
    }

    static public String parseFunctions(String command, Script script) {
	String funcs[] = StringUtils.substringsBetween(command, EXP_PREFIX, FUNCTION_SUFFIX + EXP_SUFFIX);
	if (funcs == null) {
	    return command;
	}
	for (String f : funcs) {
	    String replaceFrom = EXP_PREFIX + f + FUNCTION_SUFFIX + EXP_SUFFIX;
	    LFunction function = script.getFunction(f);
	    if (function != null) {
		String replaceTo = Library.executeFunction(function, script);
		command = command.replace(replaceFrom, replaceTo);
	    }
	}
	return command;
    }

}
